package com.example.demo.token.generator;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.domain.po.SystemUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author: 聂吉泽
 * @Description:
 * @Date: create in 2021/11/5 14:35
 */
@Component
public class TokenByHS265 implements JwtTokenGenerator{

    @Value("${cs.jwt.secret}")
    private String privateKey;

    @Override
    public String createToke(SystemUser systemUser) {
        Map<String,Object> header=new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        Calendar calendar=Calendar.getInstance();
        String token = JWT.create().withHeader(header)
                .withClaim("iss", "Service")
                .withClaim("aud", "admin")
                .withClaim("userId", "1")
                .withIssuedAt(calendar.getTime())
                .withExpiresAt(getExpires(calendar))
                .sign(Algorithm.HMAC256(privateKey));
        return token;
    }

    @Override
    public Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(privateKey)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jwt.getClaims();
    }

    public Date getExpires(Calendar calendar){
        calendar.add(Calendar.DATE,1000);
        return calendar.getTime();
    }
}
